package com.jugheadzhou.influxdb2test.aspects;

import cn.hutool.extra.servlet.ServletUtil;
import com.jugheadzhou.influxdb2test.annotations.ApiCallCounter;
import com.jugheadzhou.influxdb2test.manager.RequestTotalBucketApiManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jugheadzhou
 */
@Aspect
@Component
@Slf4j
public class ApiCallCounterAspect {
    @Resource
    private RequestTotalBucketApiManager requestTotalBucketApiManager;

    /**
     * 用ThreadLocal记录当前线程访问接口的开始时间
     */
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("@annotation(apiCallCounter)")
    public void doBefore(ApiCallCounter apiCallCounter) {
        try {
            //记录接口的开始时间
            startTime.set(System.currentTimeMillis());
            //接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //记录请求的内容
            String url = request.getRequestURI();
            String clientIP = ServletUtil.getClientIP(request, null);
            Map<String, String> tagsToAdd = new HashMap<>(3);
            tagsToAdd.put("call_url", url);
            tagsToAdd.put("call_ip", clientIP);
            Map<String, Object> fieldsToAdd = new HashMap<>(2);
            fieldsToAdd.put("value", 1D);
            requestTotalBucketApiManager.writePoint(tagsToAdd, fieldsToAdd);
        } catch (Exception e) {
            log.info("处理接口请求次数错误", e);
        }

    }

    @After("@annotation(com.jugheadzhou.influxdb2test.annotations.ApiCallCounter)")
    public void doAfter(JoinPoint joinPoint) {
        //将当前的事件减去之前的事件
        log.info("{}访问时间为：{}ms", joinPoint.getSignature().getName(), (System.currentTimeMillis() - startTime.get()));
    }

}
